package com.hmy.professor.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MessageManager;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
public class QianwenController {

    private final Generation gen;
    private final MessageManager msgManager;
    private final Constants constants;

    public QianwenController() {
        this.gen = new Generation();
        this.constants = new Constants();
        this.msgManager = new MessageManager(10);
        this.constants.apiKey = "sk-867fafc2037148c28554923fc8ac6d3e"; // 设置 API Key
    }

    @Log(title = "智慧问答", businessType = BusinessType.INSERT)
    @PostMapping(value = "/chat")
    public GenerationResult chatWithAssistant(@RequestBody String userInput) {
        List<String> responses = new ArrayList<>();
        try {
                // 创建用户消息并添加到消息管理器中
                Message userMsg = Message.builder().role(Role.USER.getValue()).content(userInput).build();
                msgManager.add(userMsg);

                // 创建 QwenParam 实例，设置对话参数
                QwenParam param = QwenParam.builder()
                        .model("qwen-max-1201")
                        .messages(msgManager.get())
                        .resultFormat(QwenParam.ResultFormat.MESSAGE)
                        .topP(0.8)
                        .enableSearch(true)
                        .build();
                // 调用 Generation 实例进行对话
                GenerationResult result = gen.call(param);
                // 添加生成的回复消息到消息管理器中
                msgManager.add(result);

                // 添加回复到列表中
                responses.add(result.getOutput().toString());

            return result;

        } catch (NoApiKeyException | ApiException | InputRequiredException e) {
            e.printStackTrace();
        }
        return null;//;responses.toArray(new String[responses.size()]);
    }
}

